<template>
	<view class="container">
		<uni-segmented-control :current="currentIndex" :values="items" style-type="text" active-color="#007aff"
			@clickItem="onClickItem" />

		<view v-if="currentIndex === 0">
			<view style="padding-top: 10px;"></view>
			<view class="tips">
				填写说明：<br>
				1、加班申请必须在加班发生前提交。<br>
				2、加班审批需要部门领导，分管领导确认后方可计为加班。
			</view>
			<view style="padding-top: 10px;"></view>
			<uni-forms ref="baseForm" :modelValue="jiabanApplyForm" border labelWidth="100px"
				label-position="left">
				<view style="padding-top: 10px;"></view>
				<uni-forms-item label="部门" required>
					<view class="text-bg">{{ userInfo.departmentName }}</view>
				</uni-forms-item>

				<uni-forms-item label="负责人" required>
						<view class="text-bg">{{ lingdao.zhijie_lingdao_name }}</view>
				</uni-forms-item>

				<uni-forms-item label="开始时间" required>
					<uni-datetime-picker @click="chuanci()" @change="chuanci2" @maskClick="chuanci2()"  type="date" return-type="string" v-model="jiabanApplyForm.startTime" />
					<view class="checkbox-bg">
						<uni-data-checkbox :localdata="jiabanlist" @change="startWuChange"/>
					</view>
				</uni-forms-item>

				<uni-forms-item label="结束时间" required>
					<uni-datetime-picker @click="chuanci()" @change="chuanci2" @maskClick="chuanci2()"  type="date" return-type="string" v-model="jiabanApplyForm.endTime" />
					<view class="checkbox-bg">
						<uni-data-checkbox :localdata="jiabanlist" @change="endWuChange"/>
					</view>
				</uni-forms-item>

				<uni-forms-item label="时长">
					<uni-easyinput :inputBorder="false" :placeholder="jiabanTimeStr()" disabled ></uni-easyinput>
				</uni-forms-item>

				<uni-forms-item label="加班事由" required>
					<uni-easyinput type="textarea"  @change="chuanci2" @input="chuanci2"  autoHeight v-model="jiabanApplyForm.reason"/>
				</uni-forms-item>

				<uni-forms-item label="加班人" required>
					<view class="text-bg">{{ userInfo.name }}</view>
				</uni-forms-item>

				<!-- 选人模块 -->
				<uni-forms-item label="审核人" required></uni-forms-item>
				<view v-for="(item, idx) in jiabanApplyForm.auditors" :key="idx">
					<uni-row>
						<uni-col :span="10">
							<view v-if="idx>0" class="step-arrow">
								<uni-icons type="bottom" size="mini" color='#a5eaff'></uni-icons>
							</view>
						</uni-col>
					</uni-row>
				
					<view class="step">
						<uni-row>
							<uni-col :span="10">
								<view class="step-info-left">{{item.stepName || item.positionName}}</view>
							</uni-col>
							<uni-col :span="14">
								<view class="step-info-right">{{item.name}}</view>
							</uni-col>
						</uni-row>
					</view>
				</view>

				<view style="padding-top: 30px;"></view>
				<button type="primary" @click="clickApply">提交</button>
			</uni-forms>
		</view>
		<view v-if="currentIndex === 1">
			<view v-for="(item, idx) in applyRecord" style="padding-bottom: 10px;" :key="idx">
				<view class="card" @click="seeDetail(idx)">
					<view class="card-title">
						<uni-row>
							<uni-col :span="20">
								<view class="card-title-left">加班</view>
							</uni-col>
							<uni-col :span="4">
								<view class="card-title-right">
									<uni-tag text="审核" size="mini" type="warning" v-if="item.sta===0&&item.chexiao==0"></uni-tag>
									<uni-tag text="通过" size="mini" type="primary" v-if="item.sta===1&&item.chexiao==0"></uni-tag>
									<uni-tag text="拒绝" size="mini" type="error" v-if="item.sta===2&&item.chexiao==0"></uni-tag>
									<uni-tag text="撤销" size="mini" type="default" v-if="item.chexiao===1"></uni-tag>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="card-body">
						<view>开始时间：{{getFormatedTimeStr(item.startTime)}}</view>
						<view>结束时间：{{getFormatedTimeStr(item.endTime)}}</view>
						<view>时长：{{item.shichang}}</view>
					</view>
					<view class="card-footer">
						<uni-row>
							<uni-col :span="24">
								<view class="card-footer-right">
									{{getFormatedTimeStr(item.createTime)}}
								</view>
							</uni-col>
						</uni-row>
					</view>
				</view>
			</view>

			<uni-load-more :status="moreStatus"></uni-load-more>
		</view>

	</view>
</template>

<script>

	import moment from 'moment'
	import {websock} from '../../net/websock'
	import {uploadconfig} from '../../const'
	import { quchongAuditors } from '../../utils/util'

	export default {
		data() {
			return {
				// 上传参数部分没有事情不要乱动
				uploadconfig,
				option: {
					url:uploadconfig.url,
					name: 'file',
					header: {},
					formData: {}
				},
				formats:uploadconfig.formats,
				instantly: uploadconfig.instantly,
				size: uploadconfig.size,
				files: new Map(),
				// 上传参数部分没有事情不要乱动
				
				jiabanlist:[{
					text: '上午',
					value: 1
				}, {
					text: '下午',
					value: 2
				}],
				currentIndex: 0,
				items: ['申请加班', '加班历史'],
				departNames: [],
				departIds: [],
				departIndex: 0,
				moreStatus: 'more',
				applyRecord: [],
				kaoqinSetting: {},
				auditors: [], // 审核人
				lingdao: {}, // 领导
				userInfo: {},
				jiabanApplyForm: {
					fuzeren: [],
					startTime: '',
					startWu: 0,
					endTime: '',
					endWu: 0,
					reason: '',
					attenders: [],
					auditors: []
				}
			}
		},
		async onReady() {
			console.log('jiayou shenqing on ready')
			
			try{

				this.userInfo = await websock.getUserInfo()

				let departList = await websock.getDepartList()
				for (let i = 0; i != departList.length; i++) {
					if (departList[i].id == 1) continue
					this.departNames.push(departList[i].name)
					this.departIds.push(departList[i].id)
				}

				this.lingdao = await websock.getLingdao()

				this.kaoqinSetting = await websock.getKaoqinSetting({})

				let auditors = await websock.getAuditors({typ: 2})
				console.log('auditors', auditors)
				this.jiabanApplyForm.auditors = auditors.slice()
				quchongAuditors(this.jiabanApplyForm.auditors)

				console.log('depart list', departList)
				this.getNewestRecord()
			}catch(e){
				uni.showToast({title: e.message})
			}
		},
		// 下拉刷新，获取最新的数据
		onPullDownRefresh() {
			console.log('onPullDownRefresh')
			if (this.currentIndex == 0) {
				uni.stopPullDownRefresh()
			} else {
				this.getNewestRecord()
			}
		},
		// 上拉刷新，获取历史数据
		onReachBottom() {
			console.log('onReachBottom')
			if (this.currentIndex == 1) {
				this.getOlderRecord()
			}
		},
		methods: {
			// 附件上传恶心的代码块-------------------------------------------------------------
			// 某文件上传结束回调(成功失败都回调)
			onuploadEnd(item) {
				console.log('fuck you',3)
				if (item.type == 'fail') {
					return uni.showToast({title: '上传失败'})}
				try {
					let res = JSON.parse(item.responseText)
					if (res.code !== 0) {
						return uni.showToast({title: res.message || 'error'})}
					this.jiabanApplyForm.attaches.push({name: item.name, path: res.data})
				} catch (err) {
					uni.showToast({title: err.message})}
				this.$forceUpdate();
			},
			// 上传进度回调
			onprogress(item) {
				this.files.set(item.name,item);// 更新当前状态变化的文件
				this.$forceUpdate();// 强制更新视图
			},
			// 文件选择回调
			onChange(files) {
				this.files = files;// 更新选择的文件 
				this.$forceUpdate();// 强制更新视图
			},
			// 穿刺一击让他们的遮罩层消失
			chuanci(){
				this.$refs.lsjUpload && this.$refs.lsjUpload.hide();
			},
			// 穿刺一击让他们的遮罩层消失
			chuanci2(){
				this.$refs.lsjUpload && this.$refs.lsjUpload.show();
				this.$forceUpdate()
			},
			// 强制重置附件按钮,万一出意外点2次按钮至少可以进去
			fuckyou(){
				this.$refs.lsjUpload && this.$refs.lsjUpload.hide()
				this.$refs.lsjUpload && this.$refs.lsjUpload.show()
				this.$forceUpdate()
			},
			// 附件上传恶心的代码块-------------------------------------------------------------
			// 获取最新的通知
			async getNewestRecord() {
				try{
					if (this.applyRecord.length == 0) {
						let res = await websock.jiabanApplyRecord({pageCount: 10})
						console.log('getRecordList list empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					} else {
						let res = await websock.jiabanApplyRecord({greaterThan: this.applyRecord[0].id,pageCount: 10})
						console.log('getRecordList list not empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					}
				}catch(e){
					uni.showToast({title: e.message})
				}
			},
			// 获取格式化时间字符串
			getFormatedTimeStr(stamp, str='MM-DD HH:mm:ss') {
				return moment(stamp).format(str)
			},
			// 获取老的数据
			async getOlderRecord() {
				this.moreStatus = 'loading'
				try{
					if (this.applyRecord.length == 0) {
						console.log('before get list empty')
						let res = await websock.jiabanApplyRecord({pageCount: 10})
						console.log('getOlderRecord list empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					} else {
						console.log('before get list not empty')
						let res = await websock.jiabanApplyRecord({lessThan: this.applyRecord[this.applyRecord.length - 1].id,pageCount: 10})
						console.log('getOlderRecord list not empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					}
				}catch(e){
					uni.showToast({title: e.message})
				}
			},
			onClickItem(e) {
				if (this.currentIndex !== e.currentIndex) {
					this.currentIndex = e.currentIndex
				}
			},
			departChange(e) {
				console.log('depart change', e.detail.value)
				this.departIndex = e.detail.value
			},
			departNameStr() {
				return this.departNames[this.departIndex] || ''
			},
			clickSelectAttender() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.jiabanApplyForm.attenders || []),
					events: {
						contactList: data => {
							console.log('select auditor', data)
							this.jiabanApplyForm.attenders = data.contactList
						}
					}
				})
			},
			clickSelectAuditor() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.jiabanApplyForm.auditors || []),
					events: {
						contactList: data => {
							console.log('select auditor', data)
							this.jiabanApplyForm.auditors = data.contactList
						}
					}
				})
			},
			deductionTime(startTime, endTime) {
				let period = []
				const start = moment(startTime, 'YYYY-MM-DD HH:mm:ss');
				const end = moment(endTime, 'YYYY-MM-DD HH:mm:ss');

				const deductionStart = moment({ hour: 17, minute: 0 });
				const deductionEnd = moment({ hour: 9, minute: 0 }).add(1, 'day');

				const currentDate = start.clone();
				while (currentDate.isBefore(end)) {
					const deductionDateStart = moment({
						year: currentDate.year(),
						month: currentDate.month(),
						date: currentDate.date(),
						hour: deductionStart.hour(),
						minute: deductionStart.minute(),
					});

					const deductionDateEnd = moment({
						year: currentDate.year(),
						month: currentDate.month(),
						date: currentDate.date() + 1,
						hour: deductionEnd.hour(),
						minute: deductionEnd.minute(),
					});

					if (deductionDateStart.isBefore(end) && deductionDateEnd.isAfter(start)) {
						const deductionStartFormatted = deductionDateStart.format('YYYY-MM-DD HH:mm:ss');
						const deductionEndFormatted = deductionDateEnd.format('YYYY-MM-DD HH:mm:ss');
						period.push({start: deductionStartFormatted, end: deductionEndFormatted})
					}

					currentDate.add(1, 'day');
				}

				return period
			},
			jiabanTimeStr() {
				console.log('jiaban time str1', this.jiabanApplyForm)
				if (this.jiabanApplyForm.startTime == '' || this.jiabanApplyForm.startWu == 0 || this.jiabanApplyForm.endTime == '' || this.jiabanApplyForm.endWu == 0) return ''
				
				if (moment(this.jiabanApplyForm.endTime).diff(moment(this.jiabanApplyForm.startTime)) < 0) return''

				if (this.jiabanApplyForm.startTime == this.jiabanApplyForm.endTime) {
					if (this.jiabanApplyForm.startWu == 2 && this.jiabanApplyForm.endWu == 1) return''
				}

				let startTime = ''
				if (this.jiabanApplyForm.startWu == 1) {
					startTime = `${moment(this.jiabanApplyForm.startTime).format('YYYY-MM-DD')} 09:00:00`
				} else if (this.jiabanApplyForm.startWu == 2) {
					startTime = `${moment(this.jiabanApplyForm.startTime).format('YYYY-MM-DD')} 13:00:00`
				}

				let endTime = ''
				if (this.jiabanApplyForm.endWu == 1) {
					endTime = `${moment(this.jiabanApplyForm.endTime).format('YYYY-MM-DD')} 13:00:00`
				} else if (this.jiabanApplyForm.endWu == 2) {
					endTime = `${moment(this.jiabanApplyForm.endTime).format('YYYY-MM-DD')} 17:00:00`
				}

				console.log('jiaban time str', startTime, endTime)
				let deductionTimes = this.deductionTime(startTime, endTime) || []
				let deductionHours = 0
				for (let i = 0; i != deductionTimes.length; i++) {
					let deductionStart = moment(deductionTimes[i].start)
					let deductionEnd = moment(deductionTimes[i].end)
					let diffHours = Math.floor((deductionEnd.valueOf() - deductionStart.valueOf()) / 1000 / 60 / 60)
					deductionHours += diffHours
				}

				let diffHours = Math.floor((moment(endTime).valueOf() - moment(startTime).valueOf()) / 1000 / 60 / 60)
				diffHours -= deductionHours
				console.log('diff hours', diffHours)
				if (diffHours < 0) return ''
				return diffHours + ' 小时'
			},
			clickSelectReceiver() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.jiabanApplyForm.fuzeren || []) + '&isSingle=1',
					events: {
						contactList: data => {
							console.log('select auditor', data)
							this.jiabanApplyForm.fuzeren = data.contactList
						}
					}
				})
			},
			async clickApply() {
				console.log('click apply', this.jiabanApplyForm)

				if (this.jiabanApplyForm.startTime == '' || this.jiabanApplyForm.startWu == 0) {
					return uni.showToast({title: '请选择开始时间'})
				}

				if (this.jiabanApplyForm.endTime == '' || this.jiabanApplyForm.endWu == 0) {
					return uni.showToast({title: '请选择结束时间'})
				}

				if (moment(this.jiabanApplyForm.endTime).diff(moment(this.jiabanApplyForm.startTime)) < 0) return uni.showToast({title: '加班时间错误'})

				if (this.jiabanApplyForm.startTime == this.jiabanApplyForm.endTime) {
					if (this.jiabanApplyForm.startWu == 2 && this.jiabanApplyForm.endWu == 1) return uni.showToast({title: '加班时间错误'})
				}

				let startTime = ''
				if (this.jiabanApplyForm.startWu == 1) {
					startTime = `${moment(this.jiabanApplyForm.startTime).format('YYYY-MM-DD')} 09:00:00`
				} else if (this.jiabanApplyForm.startWu == 2) {
					startTime = `${moment(this.jiabanApplyForm.startTime).format('YYYY-MM-DD')} 13:00:00`
				}

				let endTime = ''
				if (this.jiabanApplyForm.endWu == 1) {
					endTime = `${moment(this.jiabanApplyForm.endTime).format('YYYY-MM-DD')} 13:00:00`
				} else if (this.jiabanApplyForm.endWu == 2) {
					endTime = `${moment(this.jiabanApplyForm.endTime).format('YYYY-MM-DD')} 17:00:00`
				}

				// if (this.jiabanApplyForm.endTime - this.jiabanApplyForm.startTime < this.kaoqinSetting.jiabanMinMinutes * 1000) {
				// 	return uni.showToast({title: '时长小于' + this.kaoqinSetting.jiabanMinMinutes + '分钟'})
				// }

				// if (this.jiabanApplyForm.auditors.length == 0) {
				// 	return uni.showToast({title: '请选择审核人员'})
				// }

				let auditors = []
				for (let i = 0; i != this.jiabanApplyForm.auditors.length; i++) {
					auditors.push({uid: this.jiabanApplyForm.auditors[i].uid, stepName: this.jiabanApplyForm.auditors[i].stepName || this.jiabanApplyForm.auditors[i].positionName})
				}

				try {
					await websock.jiabanApply({
						department: this.userInfo.departmentName,
						fuzeren: this.lingdao.zhijie_lingdao,
						startTime,
						startWu: this.jiabanApplyForm.startWu,
						endTime,
						endWu: this.jiabanApplyForm.endWu,
						shichang: this.jiabanTimeStr(),
						reason: this.jiabanApplyForm.reason,
						attenders: [{uid: this.userInfo.uid, name: this.userInfo.name, avatar: this.userInfo.avatar}],
						auditors
					})
	
					uni.showToast({title: '提交成功'})
					this.jiabanApplyForm = {
						departName: '', // 部门
						fuzeren: [],
						startTime: 0,
						endTime: 0,
						reason: '',
						attenders: [],
						auditors: []
					}
	
					this.currentIndex = 1
					this.getNewestRecord()
				} catch (err) {
					uni.showToast({title: err.message || 'error'})
				}
			},
			async revertApply(idx) {
				try {
					await websock.revertJiabanApply({id: this.applyRecord[idx].id})
					this.applyRecord[idx].sta = 4
				} catch (err) {
					console.error(err)
					uni.showToast({title: err.message || 'error'})
				}
			},
			seeDetail(idx) {
				uni.navigateTo({url: `/pages/task/jiabanApplyDetail?id=${this.applyRecord[idx].id}`})
			},
			startWuChange(e) {
				console.log('start wu change', e)
				this.jiabanApplyForm.startWu = e.detail.value
			},
			endWuChange(e) {
				console.log('end wu change', e)
				this.jiabanApplyForm.endWu = e.detail.value
			}
		}
	}
</script>

<style>
@import '../common/common.css';
</style>
